/*
 * @Description: 增加弹窗
 * @Author: Zzt
 * @Date: 2022-11-07 20:15:31
 * @LastEditTime: 2022-11-14 18:09:40
 */

import { Key, useEffect, useState } from 'react';
import { Button, Form, Modal } from 'antd';
import { useReportTemplateContext } from '../../contexts/ReportTemplateContext';
import ReportTempForm, { IReportTempForm } from './common/ReportTempForm';
import { IAddReportTempParams } from '@/api/report';

const AddReport = (props: any) => {
  const { visible, onClose } = props;
  const { addReportTempFunc, selectLevel, openDesign } = useReportTemplateContext();
  const [form] = Form.useForm();

  // 保存并设计模板标志
  const [designFlag, setDesignFlag] = useState(false);

  useEffect(() => {
    form.resetFields();
  }, [visible]);

  const saveAndDesign = (flag = false) => {
    setDesignFlag(flag);
    form.submit();
  };

  const onFinish = (value: IReportTempForm) => {
    console.log({ designFlag }, value);
    const { atCode, atType, level } = selectLevel;

    const params: IAddReportTempParams = {
      ...value,
      atCode,
      atType,
      level
    };
    addReportTempFunc(params).then((res: any) => {
      onClose();
      if (designFlag) {
        openDesign(res.id);
      }
    });
  };

  return (
    <Modal
      visible={visible}
      onCancel={onClose}
      title="新增"
      footer={[
        <Button onClick={onClose} key="cancel">
          取消
        </Button>,
        <Button
          onClick={() => {
            saveAndDesign(true);
          }}
          key="saveAndDesign"
          type="primary"
        >
          保存并设计模板
        </Button>,
        <Button
          onClick={() => {
            saveAndDesign();
          }}
          key="save"
          type="primary"
        >
          保存
        </Button>
      ]}
    >
      <Form form={form} onFinish={onFinish} labelCol={{ span: 4 }} wrapperCol={{ span: 20 }}>
        <ReportTempForm visible={visible} />
      </Form>
    </Modal>
  );
};
export default AddReport;
